/*
 * 地图加载，交互的共用代码
 *
 */
$(document).ready(function() {
    initializeBaiduMap();


    resetMap();
    transGps2Location();
    markVehicle();
    map.addEventListener("zoomstart", function() {
        window.openedInfoWindow = map.getInfoWindow();
    });
    map.addEventListener("zoomend", function() {
        setZoomLevel();
        markVehicle();
        if (mapState == 1)
            reDrawTrackingPath();
        if (mapState == 2)
            reDrawHistory();
        reDrawInfoWindow();
        var position = getPosition();
        highlightVehicle(position);// 高亮显示选中的车辆
    });
});

function Gps(vehicle_no, lng, lat, direction, speed, stop_time, bl_no, datetime) {
    this.vehicle_no = vehicle_no;
    this.speed = Math.round(parseFloat(speed) / 1000 * 1.852);
    this.stop_time = stop_time;
    this.bl_no = bl_no;
    this.datetime = datetime;

    var vehicleLng = parseInt(lng) / 1000000;  //经度
    var vehicleLat = parseInt(lat) / 1000000;//纬度
    if (vehicleLng <= 180 && vehicleLng >= -180)
        this.lng = vehicleLng;
    if (vehicleLat <= 90 && vehicleLat >= -90)
        this.lat = vehicleLat;

    var direction = parseInt(direction) / 10;  //方向
    if (direction >= 0 && direction <= 360)
        this.direction = direction;


    if (typeof Gps._initialized == "undefined") {
        Gps.prototype.getPoint = function () {
            return new BMap.Point(this.lng, this.lat);
        };
        var decoder = new BMap.Geocoder();

        Gps.prototype.setLocation = function (dom_id) {
            decoder.getLocation(this.getPoint(), function (rst) {
                var s = $("#" + dom_id);
                if (s.size() > 0)
                    setLocation(rst, dom_id);
                else {
                    gRst = rst;
                    gDomId = dom_id;
                    setTimeout("setLocation(gRst, gDomId)", 1000);
                }
            });
        }
        Gps._initialized = true;
    }
}

//在dom中设置解析的地址
function setLocation(rst, dom_id) {
    if (rst != null)
        $("#" + dom_id).html(rst.address);
    else
        $("#" + dom_id).html("暂时无法取得，稍后再试");
}


//清除覆盖物，重置变量
function resetMap() {
    setZoomLevel();//初始化自定义缩放比例，目前两种比例，1小图标/2大图标
    initWindowParams();
    map.clearOverlays();
}
function setZoomLevel() {
    var zoom = map.getZoom();
    if (zoom >= 16)
        window.zoomlevel = 2;
    else
        window.zoomlevel = 1;
}
function initWindowParams() {
    window.mapState = 0;  //地图状态，0表示无状态，1表示跟踪，2表示查看历史
    window.markers = {};      //初始化保存标记的集合
    window.trackingVehicles = {};//记录正在跟踪的车辆
    window.trackingVGps = {};//缓存正在跟踪的车辆的gps(未绘制到地图上)
    window.vehicleGpsOnMap = {};//记录当前车辆的最新绘制到地图上的位置
    window.vehiclePath = {};//记录地图上车辆跟踪轨迹对象，即折线对象

    TRACK_PATH_MAX_LENGTH = 20;
    HISTORY_PATH_MAX_POINT_COUNT_ZOOM1 = 75;
    HISTORY_PATH_MAX_POINT_COUNT_ZOOM2 = 130;
}
//创建和初始化地图函数：
function initializeBaiduMap() {
    createMap();//创建地图
    setMapEvent();//设置地图事件
    addMapControl();//向地图添加控件
}

//创建地图函数：
function createMap() {
    var map = new BMap.Map("map_container");//在百度地图容器中创建一个地图
    var point = new BMap.Point(122.085, 37.509); // 创建点坐标
    map.centerAndZoom(point, 13);//设定地图的中心点和坐标并将地图显示在地图容器中
    window.map = map;//将map变量存储在全局
}

//地图事件设置函数：
function setMapEvent() {
    map.enableScrollWheelZoom();//启用地图滚轮放大缩小
    map.enableKeyboard();//启用键盘上下左右键移动地图
    map.enableContinuousZoom(); //设置缩放效果
    map.setDefaultCursor();  //设置默认鼠标
}

//地图控件添加函数：
function addMapControl() {
    //向地图中添加缩放控件
    var ctrl_nav = new BMap.NavigationControl({anchor:BMAP_ANCHOR_TOP_LEFT, type:BMAP_NAVIGATION_CONTROL_LARGE});
    map.addControl(ctrl_nav);
    //向地图中添加缩略图控件
    var ctrl_ove = new BMap.OverviewMapControl({anchor:BMAP_ANCHOR_BOTTOM_RIGHT, isOpen:0});
    map.addControl(ctrl_ove);
    //向地图中添加比例尺控件
    var ctrl_sca = new BMap.ScaleControl({anchor:BMAP_ANCHOR_BOTTOM_LEFT});
    map.addControl(ctrl_sca);
}

function markVehicle(vehicleNo) {
    if (vehicleNo == undefined || vehicleNo == null) {
        if ($.isEmptyObject(window.vehicleGpsOnMap))
            window.vehicleGpsOnMap = getVehicleGpsFromPage();
        window.markers = {};
        map.clearOverlays();
        $.each(vehicleGpsOnMap, function (vehicleNo, gps) {
            //  车号、经度、纬度、方向
            drawPosition(gps[gps.length - 1]);
        });
    } else {
        // 定位到该车所在位置
        var marker = markers[vehicleNo];
        if(!marker){
            markVehicle();
            marker = markers[vehicleNo];
        }
        if (marker == undefined || marker == null) {
            show_notice("没有数据，暂时无法定位车辆");
            return false;
        }
        else {
            map.panTo(marker.getPosition());
            highlightVehicle(marker.getPosition());
            openVehicleInfoWin(vehicleNo, marker.getPosition());
        }
        return true;
    }
    //定位本页提单中所有的车辆的位置
}
//返回车辆位置数组
function getVehicleGpsFromPage() {
    var vehicleNos = {};
    $("[class^=vehicle_gps_]").each(function () {
        var gps = this.value.split(',');
        var vehicleNo = gps[0];
        var vehicleLng = gps[1];  //经度
        var vehicleLat = gps[2];//纬度
        var direction = gps[3];  //方向
        var speed = gps[4];  //速度
        var stopTime = gps[5];  //停车时间
        var time = gps[6];  //发送时间

        if (vehicleNo != "") {
            if (!vehicleNos[vehicleNo]) {
                vehicleNos[vehicleNo] = [new Gps(vehicleNo, vehicleLng, vehicleLat, direction, speed, stopTime, "", time)];
            }
        }
    });
//    console.log("vehicle gps from the page:", vehicleNos);
    return vehicleNos;
}

//根据经纬度在地图上画车辆
function highlightVehicle(position) {
    if(!position)
        return;
//显示选中框
    if (typeof(highLightMarker) != 'undefined' && highLightMarker)
        map.removeOverlay(highLightMarker);
    highLightMarker = new BMap.Marker(position, {icon:new BMap.Icon("/assets/highlight.png", new BMap.Size(50, 50))   });
    highLightMarker.setZIndex(-10000000);
    map.addOverlay(highLightMarker);
}
function openVehicleInfoWin(vehicleNo, position) {
//显示信息窗口
    var opts = {
        width:260, // 信息窗口宽度
        height:220, // 信息窗口高度
        title:"<b>详细信息</b>"  // 信息窗口标题
    }

    var info = getInfoWindowInfo(vehicleNo, position);
    var infoWindow = new BMap.InfoWindow(info, opts);  // 创建信息窗口对象
    infoWindow.addEventListener('clickclose', function () {
        window.openedInfoWindow = undefined;
    });
    infoWindow.addEventListener('open', function () {
        window.openedInfoWindow = infoWindow;
    });
    map.openInfoWindow(infoWindow, position);      // 打开信息窗口
}

function drawPosition(gps) {
    if (gps == undefined || gps == null)
        return false;
    var lng = gps.lng;
    var lat = gps.lat;
    var vehicleNo = gps.vehicle_no;
    var direction = gps.direction;
//    console.log("draw postion:" + vehicleNo + "-经度-" + lng + "--纬度-" + lat + "on level:" + zoomlevel);
    if (lng == undefined || lng == "" || lat == undefined || lat == "")
        return false;
    var vehiclePoint = new BMap.Point(lng, lat);
    // 创建图标对象
    var vehicleIcon = getVehicleIcon(direction);
    // 创建标注对象并添加到地图
    var vehicleMarker = new BMap.Marker(vehiclePoint, {icon:vehicleIcon});

    //清除已经在图上的标注
    map.removeOverlay(window.markers[vehicleNo]);
    //添加标注
    map.addOverlay(vehicleMarker);
    //保存到markers变量中
    window.markers[vehicleNo] = vehicleMarker;

    //绑定click事件
    vehicleMarker.addEventListener("click", function () {
        highlightVehicle(vehicleMarker.getPosition());
        openVehicleInfoWin(vehicleNo, vehicleMarker.getPosition());
    });
}

function getNewestGps(vehicleNo) {
    var gpses = vehicleGpsOnMap[vehicleNo];
    if ($.isArray(gpses)) {
        var gps = gpses[gpses.length - 1];
    }
    return gps;
}

function getGpsByPosition(vehicleNo, point) {
    var gps = null;
    $.each(vehicleGpsOnMap[vehicleNo], function (index, tempGps) {
        if (tempGps.getPoint().equals(point)) {
            gps = tempGps;
            return false;
        }
    });
    return gps;
}
function getInfoWindowInfo(vehicleNo, position) {
    if (vehicleNo == undefined || vehicleNo == null || $.trim(vehicleNo) == "")
        return "暂无信息";
    else {

        var ctnNos = [];
        var speed = '';
        var time = "";
        var gps = getGpsByPosition(vehicleNo, position);
        var blNo = gps.bl_no;
        if (gps != undefined && gps != null) {
            gps.setLocation("location");
            speed = gps.speed;
            time = gps.datetime;
        }
        $(".vehicle_no").each(function () {
            if (this.value == vehicleNo) {
                ctnNos.push($(this).next().val());
                if (!blNo) {
                    var blDiv = $(this).closest(".row").find(".s-bill-info .bill-code");
                    blNo = $.trim(blDiv.text());
                }
            }
        });

        var info = [];
        info.push("<p>车号: " + vehicleNo + "</p>");
        info.push("<p>当前位置: <span id='location'>" + "<img src='/assets/loading.gif' alt='正在解析地址'>正在解析…" + "</span></p>");
        info.push("<p>速度: " + speed + "(km/h)</p>");
        info.push("<p>时间: " + time + "</p>");
        //如果不是显示历史轨迹状态下
        if (mapState != 2) {
            info.push("<p>提单号: " + blNo + "</p>");
            if(ctnNos.length > 0)
                info.push("<p>集装箱: " + ctnNos + "</p>");
            //如果正在跟踪
            if (trackingVehicles[vehicleNo])
                info.push("<input type='button' id = '" + vehicleNo + "' onclick=toggleTrack('" + vehicleNo + "','stopTrack'); value='取消跟踪'/>");
            else
                info.push("<input type='button' id = '" + vehicleNo + "' onclick=toggleTrack('" + vehicleNo + "','track'); value='跟踪'/>");
        }

        info.push("<input type='hidden' value='" + vehicleNo + "'>");
        return info.join("");
    }

}


function getVehicleIcon(direction) {
    if (direction == undefined || direction == "") {
        direction = 370;
    }

    var direc = parseFloat(direction);
    var imagPath = "/assets/vehicles/vehicle_default.png";
    //大图标
    if (zoomlevel == 2) {
        if ((direc >= 345 && direc <= 360) || (direc >= 0 && direc < 15))
            imagPath = "/assets/vehicles/vehicle_detail.png";
        else if (direc >= 15 && direc < 45)
            imagPath = "/assets/vehicles/vehicle_detail_30.png";
        else if (direc >= 45 && direc < 75)
            imagPath = "/assets/vehicles/vehicle_detail_60.png";
        else if (direc >= 75 && direc < 105)
            imagPath = "/assets/vehicles/vehicle_detail_90.png";
        else if (direc >= 105 && direc < 135)
            imagPath = "/assets/vehicles/vehicle_detail_120.png";
        else if (direc >= 135 && direc < 165)
            imagPath = "/assets/vehicles/vehicle_detail_150.png";
        else if (direc >= 165 && direc < 195)
            imagPath = "/assets/vehicles/vehicle_detail_180.png";
        else if (direc >= 195 && direc <= 225)
            imagPath = "/assets/vehicles/vehicle_detail_210.png";
        else if (direc >= 225 && direc < 255)
            imagPath = "/assets/vehicles/vehicle_detail_240.png";
        else if (direc >= 255 && direc < 285)
            imagPath = "/assets/vehicles/vehicle_detail_270.png";
        else if (direc >= 285 && direc < 315)
            imagPath = "/assets/vehicles/vehicle_detail_300.png";
        else if (direc >= 315 && direc < 345)
            imagPath = "/assets/vehicles/vehicle_detail_330.png";
        else
            return new BMap.Icon(imagPath, new BMap.Size(10, 10));
        return new BMap.Icon(imagPath, new BMap.Size(60, 60));
    } else {
        //小图标
        if ((direc >= 345 && direc <= 360) || (direc >= 0 && direc < 15))
            imagPath = "/assets/vehicles/vehicle_thumbnail.png";
        else if (direc >= 15 && direc < 45)
            imagPath = "/assets/vehicles/vehicle_thumbnail_30.png";
        else if (direc >= 45 && direc < 75)
            imagPath = "/assets/vehicles/vehicle_thumbnail_60.png";
        else if (direc >= 75 && direc < 105)
            imagPath = "/assets/vehicles/vehicle_thumbnail_90.png";
        else if (direc >= 105 && direc < 135)
            imagPath = "/assets/vehicles/vehicle_thumbnail_120.png";
        else if (direc >= 135 && direc < 165)
            imagPath = "/assets/vehicles/vehicle_thumbnail_150.png";
        else if (direc >= 165 && direc < 195)
            imagPath = "/assets/vehicles/vehicle_thumbnail_180.png";
        else if (direc >= 195 && direc <= 225)
            imagPath = "/assets/vehicles/vehicle_thumbnail_210.png";
        else if (direc >= 225 && direc < 255)
            imagPath = "/assets/vehicles/vehicle_thumbnail_240.png";
        else if (direc >= 255 && direc < 285)
            imagPath = "/assets/vehicles/vehicle_thumbnail_270.png";
        else if (direc >= 285 && direc < 315)
            imagPath = "/assets/vehicles/vehicle_thumbnail_300.png";
        else if (direc >= 315 && direc < 345)
            imagPath = "/assets/vehicles/vehicle_thumbnail_330.png";
        else
            return new BMap.Icon(imagPath, new BMap.Size(10, 10));
//        console.log(imagPath);
        return new BMap.Icon(imagPath, new BMap.Size(20, 20));
    }

}

//地址解析，经纬度转换为地址
//解析的结果写入集装箱列表的地址栏中
function transGps2Location() {
    $("[class^=vehicle_gps_]").each(function () {
        var gps = this.value.split(',');
        var vehicleLng = gps[1] / 1000000;  //经度
        var vehicleLat = gps[2] / 1000000;//纬度
        if(isNaN(vehicleLat) || isNaN(vehicleLng))
           return;
        var locationContainer = this;
        var point = new BMap.Point(vehicleLng, vehicleLat);
        var decoder = new BMap.Geocoder();
        decoder.getLocation(point, function (rst) {
            if (rst)
                $(locationContainer).parent().prev().html(rst.address);
        });
    });
}


//根据车号获取跟踪状态下最新gps数据或者获取当前打开的信息框的gps位置
function getPosition(vehicleNo) {
    var position;
    if (mapState == 1)
        try{
            position = getNewestGps(vehicleNo).getPoint();
            if(position)
                return position;
        }catch(e) {
        }
    if(openedInfoWindow)
        position = openedInfoWindow.getPosition();
    return position;
}
function reDrawInfoWindow(vehicleNo) {

    //  var infowindow = map.getInfoWindow();
    //绘制动态的，如点击跟踪或取消按钮时
//    if (infowindow != null && vehicleNo != undefined) {
//        infowindow.setContent(getInfoWindowInfo(vehicleNo, infowindow.getPosition()));
//        map.openInfoWindow(infowindow, markers[vehicleNo].getPosition());
//    }
   // else {
        //绘制静态的，如缩放地图时
        //车辆跟踪过程中，信息框的重新绘制
        if (openedInfoWindow != undefined && openedInfoWindow != null) {
            try {
                if(!vehicleNo)
                    var vehicleNo = $(openedInfoWindow.getContent()).last().val();
                openedInfoWindow.setContent(getInfoWindowInfo(vehicleNo, openedInfoWindow.getPosition()));
                //跟踪状态下显示到最新的gps位置
                var position = getPosition(vehicleNo);
                //highlightVehicle(position);// 高亮显示选中的车辆
                map.openInfoWindow(openedInfoWindow, position);
            }
            catch (exception) {
//                console.log(exception.message);
            }
        }
    //}

}

//跟踪车辆
function track(vehicleNo) {

    var canTrack = markVehicle(vehicleNo);
    if (canTrack) {
        $.get("/maps/track_register", { vehicle_no:vehicleNo, session_id:window.sessionId },
            function (data) {
                show_notice(data.notice);

                if (data.status == 'ok') {
                    window.mapState = 1;
                    window.trackingVehicles[vehicleNo] = true;
                    window.sessionId = data.session_id
                    //重绘窗口，设置按钮为取消跟踪
                    reDrawInfoWindow(vehicleNo);

                    //设置定时请求跟踪数据函数
                    if (!window.getGpsInterval) {
                        //定时器，间隔1s
                        // 获取车辆gps数据，缓存到全局变量 trackingVGps（数组形式，数组中存放gps对象)
                        var fetchTimes = 0;
                        var fetchexceptionTimes = 0;
                        var interval = setInterval(function () {
                            $.get("/maps/track_fetch_gps", {session_id:window.sessionId}, function (gpsData) {
                                var status = gpsData.status;
                                if (status == "empty") {
                                    fetchTimes++;
                                    if (fetchTimes > 10) {
                                        show_notice(gpsData.notice);
                                        fetchTimes = 0;
                                        fetchexceptionTimes = 0;
                                    }
                                } else if (status == "exception") {
                                    fetchexceptionTimes++;
                                    if (fetchexceptionTimes > 10) {
                                        show_notice(gpsData.notice);
                                        fetchexceptionTimes = 0;
                                        fetchTimes = 0;
                                    }
                                } else {
                                    try {
//                                    console.log(gpsData);
                                        $.each(gpsData.gps_objs, function (vehicleNo, gpsArray) {
                                            for (var i = 0; i < gpsArray.length; i++) {
                                                var gpsObj = gpsArray[i];
                                                if (!$.isArray(window.trackingVGps[vehicleNo]))
                                                    trackingVGps[vehicleNo] = [];
                                                trackingVGps[vehicleNo].push(new Gps(vehicleNo, gpsObj.lng, gpsObj.lat, gpsObj.direction,
                                                    gpsObj.speed, "", "", gpsObj.datetime));
                                            }
                                        });

                                    } catch (e) {
//                                    console.log(e.message);
                                    }
                                    fetchTimes = 0;
                                    fetchexceptionTimes = 0;
                                }
                            });
                            return false;
                        }, 1000);
                        window.getGpsInterval = interval;
                    }


                    //设置定时绘制车辆位置的定时器
                    if (!window.drawVehicleInterval) {
                        //定时器，间隔0.5s
                        //将缓存的车辆gps坐标绘制到地图上，实现跟踪效果
                        var interval = setInterval(function () {
                            if (window.trackingVGps != undefined && window.trackingVGps != null) {

                                $.each(trackingVGps, function (vehicleNo) {
                                    var gpsObj = trackingVGps[vehicleNo].shift();
//                                console.log("tracking and draw gps", gpsObj);
                                    if (gpsObj != null) {
                                        if (!$.isArray(vehicleGpsOnMap[vehicleNo])) {
                                            vehicleGpsOnMap[vehicleNo] = [];
                                        }//存储最新绘制到地图上的位置
                                        vehicleGpsOnMap[vehicleNo].push(gpsObj);//存储最新绘制到地图上的位置
                                        while (vehicleGpsOnMap[vehicleNo].length >= TRACK_PATH_MAX_LENGTH) {
                                            vehicleGpsOnMap[vehicleNo].shift();
                                        }
                                        drawTrackingPath(gpsObj);
                                    }
                                });


                            }
                            return false;
                        }, 500);
                        window.drawVehicleInterval = interval;
                    }
                }

            });
    } else
        show_notice("车辆暂时无法定位，不能跟踪");
    return false;
}

function cancleTrack(vehicleNo) {
    if (window.sessionId) {
        $.get("/maps/track_unregister", {vehicle_no:vehicleNo, session_id:window.sessionId}, function (data) {

            show_notice(data.notice);//如取消成功
            if (data.status == 'ok') {
                window.trackingVehicles[vehicleNo] = false;
                window.mapState = 0;

                reDrawInfoWindow(vehicleNo);
                var tracking = false;
                $.each(trackingVehicles, function (vehicleNo, tracked) {
                    tracking = tracking || tracked;
                });
                if (!tracking) {

                    $("#sessionId").val("");
                    if (getGpsInterval != undefined && getGpsInterval != null) {
                        clearInterval(getGpsInterval);
                        window.getGpsInterval = null;
                    }
                    //取消定时请求车辆gps数据
                    if (drawVehicleInterval != undefined && drawVehicleInterval != null) {
                        clearInterval(drawVehicleInterval);
                        window.drawVehicleInterval = null;
                    }
                    //清空缓存的gps数据
                    window.trackingVGps = {};
                }
            }
        });
    }
    return false;
}
//跟踪过程中绘制轨迹
function drawTrackingPath(gpsObj) {
    if (gpsObj != undefined && gpsObj != null) {
        drawPosition(gpsObj);
//        highlightVehicle(gpsObj.getPoint());
        //绘制轨迹
        var vehicleNo = gpsObj.vehicle_no;
        map.removeOverlay(vehiclePath[vehicleNo]);

        var pathPoints = vehicleGpsOnMap[vehicleNo];
        vehiclePath[vehicleNo] = new BMap.Polyline(pathPoints, {strokeColor:"blue", strokeWeight:1, strokeOpacity:0.5});
        map.addOverlay(vehiclePath[vehicleNo]);
        //轨迹绘制结束
        reDrawInfoWindow();
    }
}

function reDrawTrackingPath() {
    //轨迹重新绘制  , 如缩放时
    $.each(vehicleGpsOnMap, function (vehicleNo, gpsArray) {
        if ($.isArray(gpsArray))
            var gpsObj = gpsArray[gpsArray.length - 1];
        if (gpsObj == undefined || gpsObj == null)
            return false;
        if (gpsArray.length > 1) {
            //绘制轨迹
            var pathPoints = gpsArray;

            vehiclePath[vehicleNo] = new BMap.Polyline(pathPoints, {strokeColor:"blue", strokeWeight:1, strokeOpacity:0.5});
            map.addOverlay(vehiclePath[vehicleNo]);
            //轨迹绘制结束
        }
    });
}

function toggleTrack(vehicleNo, cmd) {
    if (cmd == "track") {
        $(".track_link_" + vehicleNo).hide();
        $(".cancel_track_" + vehicleNo).show();
        track(vehicleNo);
    } else {
        $(".track_link_" + vehicleNo).show();
        $(".cancel_track_" + vehicleNo).hide();
        cancleTrack(vehicleNo);
    }
}


// 获取提单的提单历史
function show_history(bl_id) {
    $('#bl_history_' + bl_id + '_content').html("请等待……\n");
    $('#bl_history_' + bl_id).slideDown('fast');
    $.get(
        "/bls/bl_history",
        {bl_id:bl_id},
        function (bl_history) {
            $('#bl_history_' + bl_id + '_content').html(bl_history);
            return false;
        }
    )
}
// 获取集装箱的历史
function get_ctn_history(blNo, ctnNo) {
    if (ctnNo == undefined || ctnNo == null) {
        return false;
    }
    if (blNo == undefined || blNo == null) {
        return false;
    }
    show_shelter();
    $.get("/bl_containers/ctn_history", {bl_no:blNo, ctn_no:ctnNo}, function (data) {
        hide_shelter();
        show_notice(data.notice);
        var status = data.status;
        if (status == "exception") {
            return false;
        }
        if (status == "ok") {
            $("#history_win").html(data.ctn_history);
            show_ctn_history_hide_bl(ctnNo);
            if (data.gps_history == null) {
                data.gps_history = [];
            }
            show_shelter("绘制历史轨迹，请稍后……");
            drawHistory(data.gps_history);

            hide_shelter();
        }
    });
}

// 此处传入的参数为object类型数组
function drawHistory(gpses) {
    resetMap();
    window.mapState = 2;
//    console.log("start draw path", new Date().getTime());
    var points = {};
    $.each(gpses, function (index, gpsObj) {
        var gps = new Gps(gpsObj.vehicle_no, gpsObj.longitude, gpsObj.latitude, gpsObj.direction, gpsObj.speed, gpsObj.stop_time,"", gpsObj.time);
        if (!$.isArray(window.vehicleGpsOnMap[gpsObj.vehicle_no])) {
            window.vehicleGpsOnMap[gpsObj.vehicle_no] = [];
            points[gpsObj.vehicle_no] = [];
        }
        points[gpsObj.vehicle_no].push(gps.getPoint());
        window.vehicleGpsOnMap[gpsObj.vehicle_no].push(gps);
    });

    $.each(vehicleGpsOnMap, function (vehicleNo) {
        //数据少于两个点则直接返回，不进行绘制
        if(vehicleGpsOnMap[vehicleNo].length < 2)
            return false;
        window.vehiclePath[vehicleNo] = new BMap.Polyline(points[vehicleNo], {strokeColor:"red", strokeStyle:'dashed', strokeWeight:3, strokeOpacity:0.5});
        drawPathAndCircleOnMap(vehicleNo, window.vehiclePath[vehicleNo]);
        map.panTo(points[vehicleNo][0]);
    });
//    console.log("end draw path", new Date().getTime());
}

function reDrawHistory() {
    map.clearOverlays();
    $.each(vehiclePath, function (vehicleNo, vehiclePath) {
        drawPathAndCircleOnMap(vehicleNo, vehiclePath);
    });
}

function drawCircle(circlePoint, vehicleNo) {

    var circle = new BMap.Circle(circlePoint, 15);
    map.addOverlay(circle);
    circle.addEventListener('click', function () {
        openVehicleInfoWin(vehicleNo, circlePoint);
    });
}
function drawHisPoint(factor, vehicleNo, maxPointCount) {

    if (factor <= 1) {
        //实际点数目不到最大值
        $.each(vehicleGpsOnMap[vehicleNo], function (index, gps) {
            drawCircle(gps.getPoint(), vehicleNo);
        });
    }
    else {
        for (var index = 0; index < maxPointCount; index++) {
            var gps = vehicleGpsOnMap[vehicleNo][Math.round(index * factor)];
            drawCircle(gps.getPoint(), vehicleNo);
        }
    }
}
function drawPathAndCircleOnMap(vehicleNo, vehiclePath) {

    var points = vehiclePath.getPath();

    //绘制历史轨迹
    var startPoint = points[0];
    var endPoint = points[points.length - 1];

    var startMarker = new BMap.Marker(startPoint, {icon:new BMap.Icon("/assets/start.png", new BMap.Size(42, 34))});
    startMarker.addEventListener("click", function () {
        openVehicleInfoWin(vehicleNo, startMarker.getPosition());
    });
    var endMarker = new BMap.Marker(endPoint, {icon:new BMap.Icon("/assets/end.png", new BMap.Size(42, 34))});
    endMarker.addEventListener("click", function () {
        openVehicleInfoWin(vehicleNo, endMarker.getPosition());
    });
    map.addOverlay(startMarker);
    map.addOverlay(endMarker);

    map.addOverlay(vehiclePath);


    //绘制轨迹上的点
    //思路：根据缩放级别确定点的数目，缩放级别最大绘制最多130个点以保证效率

    var pathPointCount = points.length;
    var factor2 = 1;  //二级绘制最多点
    if (pathPointCount > HISTORY_PATH_MAX_POINT_COUNT_ZOOM2)
        factor2 = pathPointCount / HISTORY_PATH_MAX_POINT_COUNT_ZOOM2;
    var factor1 = 1;    //一级绘制最多点
    if (pathPointCount > HISTORY_PATH_MAX_POINT_COUNT_ZOOM1)
        factor1 = pathPointCount / HISTORY_PATH_MAX_POINT_COUNT_ZOOM1;
    switch (zoomlevel) {
        case 2:
            drawHisPoint(factor2, vehicleNo, HISTORY_PATH_MAX_POINT_COUNT_ZOOM2);
        case 1:
            drawHisPoint(factor1, vehicleNo, HISTORY_PATH_MAX_POINT_COUNT_ZOOM1);
    }
}

//视野内查车
function queryVehicleInView(){
    // 获取视野内的坐标，转换成真正的经纬度
    var bounds = map.getBounds();
    var swPoint = bounds.getSouthWest();  //返回矩形区域的西南角
    var nePoint = bounds.getNorthEast(); //返回矩形区域的东北角。

    getVehicleInZone(swPoint, nePoint);
}

//根据区间范围向后台请求车辆查询
function getVehicleInZone(swPoint, nePoint){
    //向后台发送请求，获取此范围内的车辆
    $.get("/motorcade_maps/vehicles_in_area",{lng_min:swPoint.lng, lng_max: nePoint.lng, lat_min: swPoint.lat, lat_max: nePoint.lat},
        function(rst){
            show_notice(rst.notice);
            if(rst.status == 'success'){
                var vehicles = rst.vehicles;
                console.log(vehicles);
                window.vehicleGpsOnMap = {};
                $.each(vehicles, function(vehicleNo, gpsObj){
                    vehicleGpsOnMap[vehicleNo] =  [new Gps(vehicleNo, gpsObj.lng, gpsObj.lat, gpsObj.direction, gpsObj.speed, "", gpsObj.bl_no,  gpsObj.datetime)];
                });
                markVehicle();
            }

        }, 'json');
}

//框选范围查车,查询完成后自动关闭
function search_in_rectangle(){
    var keyword = "车辆" ;
    var pullBox = new BMapLib.SearchInRectangle(map,keyword,{
        renderOptions:{
            map: map,
            strokeWeight: 2,
            strokeColor: "red",
            fillColor:"white",
            opacity: 0.5,
            followText: "拖拽鼠标搜索"+ keyword +"",
            autoClose: true,
            autoViewport: false,
            alwaysShowOverlay: false
        }
    });
    pullBox.setLineStyle("dashed");
    pullBox.open();
}

//根据车号查找车辆历史并绘制到地图上
function queryVehicleHistoryInPeriod(vehicleNo,startTime, endTime){
    if(!vehicleNo) {
        show_notice("页面错误，刷新再试");
        return;
    }
    show_shelter();
    $.get("/motorcade_maps/vehicle_history", {vehicle_no: vehicleNo, start_time:startTime, end_time:endTime },
        function(rst){
            hide_shelter();
            show_notice(rst.notice);
            if(rst.status == "success"){
                var gpses = rst.gps_history;
                if(gpses && gpses.length > 0){
                    show_shelter("绘制历史轨迹，请稍后……");
                    drawHistory(gpses);
                    hide_shelter();
                }
            }
        }, 'json');
    return;
}



/*
* 地图页面上的全屏操作
*
*/
function hideBgDiv() {
    $("div.site-nav").hide();
    $("div.header").hide();
    $("div.web-title").hide();
    $("div.search-btn-div").hide();
    $("div.footer").hide();
    $(".fake-body").css("width", "98%")
}
function restoreBgDiv() {
    $("div.site-nav").show();
    $("div.header").show();
    $("div.web-title").show();
    $("div.search-btn-div").show();
    $("div.footer").show();
    $(".fake-body").css("width", 1000);
}
function updateFullMapSize() {
    var width = $(window).width() - 2;
    var blWidth = $("#rst_info_view").width();
    var mapWidth = width - blWidth;
    $("#map").width(width);
    $("#map_container").width(mapWidth);
    $("html, body").css("height", '100%');
    hideBgDiv();
}
function fullMap(){
    $(".fake-body").css("min-height", 0);
    $(".fake-body").css("position", "static");
    $("#map").css({position:"absolute"});

    updateFullMapSize();
    $("#map").css("top", 0);
    $("#map").css("left", 0);
    $("#map").css("z-index", 99999);

    $("#fullMapBtn").hide();
    $("#exitFullMapBtn").show();

    $(window).bind('resize', function(){
        updateFullMapSize();
    })
}

function exitFullMap(){
    $(window).unbind('resize') ;
    restoreBgDiv();
    $("#exitFullMapBtn").hide();
    $("#fullMapBtn").show();
    $(".fake-body").css("min-height", 700);
    $(".fake-body").css("position", "relative");
    $("#map").css("position", "relative");
    $("#map").css("left", 0);
    $("#map").css({border:"1px solid #C4D5E0", width:"998", height:"550"});
    $("#map").width("100%");
    $("#mapC").width("100%");
    $("#map").css("zIndex", 1);
    $("#map_container").width(700);
    $("#map_result").height(520);
    $("#map-table tr td").height(520);
    $("html, body").css("height", "auto");
}
/*
 * 地图页面上的全屏操作结束
*/